import { useEquipmentInfoStore } from '@/stores/equipment-info-store';
import { onUnmounted, ref, onMounted } from 'vue';
import Worker from './worker/index.js?worker'; //
export const useLineChart = ({ id, totalCount, type, initNum, totalPreSecond, onceUpdate, timeOut, oldUpdate, emptyNum }) => {
    const store = useEquipmentInfoStore();
    let data = [];
    const commonChartRef = ref();
    const setOption = () => {
        commonChartRef.value?.setOption({
            series: [
                {
                    data: data.map((item, index) => [index, item])
                }
            ]
        });
    };
    let worker = new Worker(); // 开启副线程
    const runningWorker = () => {
        // 先画横线
        worker.postMessage({
            type: 'start',
            data: [],
            totalCount,
            initNum,
            totalPreSecond,
            onceUpdate,
            timeOut,
            oldUpdate,
            emptyNum
        });
        worker.onmessage = e => {
            let currentData = [];
            switch (e.data.type) {
                case 'start':
                    data = e.data.data;
                    setOption();
                    break;
                case 'interval':
                    currentData = store.personLineData(type, id);
                    worker.postMessage({
                        type: 'interval-running',
                        data: [...data],
                        currentData: [...currentData]
                    });
                    break;
                case 'running-first':
                    store.shiftData(type, id, e.data.length);
                    break;
                case 'running':
                    data = e.data.data;
                    store.shiftData(type, id, e.data.length);
                    setOption();
                    break;
                default:
                    break;
            }
        };
    };
    onMounted(() => {
        runningWorker();
    });
    const visibilitychange = () => {
        if (document.visibilityState == 'hidden') {
            worker.postMessage({
                type: 'stop'
            });
            worker.terminate();
        }
        if (document.visibilityState == 'visible') {
            worker = new Worker();
            runningWorker();
        }
    };
    document.addEventListener('visibilitychange', visibilitychange);
    onUnmounted(() => {
        worker.postMessage({
            type: 'stop'
        });
        worker.terminate();
        document.removeEventListener('visibilitychange', visibilitychange);
    });
    return {
        commonChartRef,
        data,
        setOption
    };
};
